package controller;

import view.UserPanel;
import view.TaskFrame;
import modle.User;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.List;

import javax.swing.JCheckBox;
import javax.swing.JOptionPane;
import javax.swing.JTabbedPane;

import dao.EmailDao;
import dao.EventDao;
import dao.TaskDao;
import dao.UserDao;

public class UserController implements ActionListener {
	TaskFrame taskFrame;
	UserPanel userPanel = null;

	public UserController(UserPanel userPanel) throws SQLException {
		this.taskFrame = userPanel.getTaskFrame();
		this.userPanel = userPanel;
	}

	public void actionPerformed(ActionEvent event) {
		// TODO Auto-generated method stub
		if (event.getSource() == userPanel.getLoginButton()) {
			try {
				login();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		if (event.getSource() == userPanel.getNewButton()) {
			try {
				addUser();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		if (event.getSource() == userPanel.getModifyButton()) {
			try {
				modifyUser();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		if (event.getSource() == userPanel.getDeleteButton()) {
			try {
				deleteUser();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		if (event.getSource() == userPanel.getAutoLoginCheckBox()) {
			JCheckBox checkBox = userPanel.getAutoLoginCheckBox();
			try {
				changeAutoLogin(checkBox.isSelected());
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	@SuppressWarnings("deprecation")
	private void addUser() throws SQLException {
		User user = new User();
		UserDao userDao = new UserDao();
		// get UserName and judge if it is legal;
		user.setUserName(userPanel.getUserNameField().getText());
		if (user.getUserName().equals("")) {
			showMessage("UserName can't be blank!");
			return;
		}
		// get UserPassword and judge if it is legal;
		user.setUserPassword(userPanel.getPasswordField().getText());
		if (user.getUserPassword().equals("")) {
			showMessage("Password can't be blank!");
			return;
		}

		int i = userDao.save(user);

		if (i > 0) {
			user = userDao.findByUserName(user.getUserName()).get(0);
			loadUser(user);
			setUser(user);
			loginSuccessfully();
		} else {
			addUserFailed();
		}
		userDao.closeConnection();
	}

	private void addUserFailed() {
		// TODO Auto-generated method stub
		showMessage("Add User Failed");
		taskFrame.init();
	}

	private void changeAutoLogin(boolean bool) throws SQLException {
		UserDao userDao = new UserDao();

		if (bool) {
			List<User> users = userDao.findByIsAutoLogin(1);
			User user = null;
			if (users != null && !users.isEmpty())
				user = users.get(0);
			if (user != null) {
				user.setIsAutoLogin((byte) 0);
				userDao.update(user);
			}
			getUser().setIsAutoLogin((byte) 1);
		} else {
			getUser().setIsAutoLogin((byte) 0);
		}
		if (userDao.update(getUser()) > 0) {
			if (bool)
				showMessage("Set AutoLogin Successfully!");
			else
				showMessage("Cancel AutoLogin Successfully!");
		} else {
			showMessage("Modify AutoLogin Failed");
			getUser().setIsAutoLogin(bool ? (byte) 0 : (byte) 1);
			setUserToPanel(getUser());
		}
		userDao.closeConnection();
	}

	private void deleteUser() throws SQLException {
		// TODO Auto-generated method stub
		UserDao userDao = new UserDao();
		if (userDao.delete(getUser()) > 0) {
			showMessage("Delete Successfully!");
			taskFrame.init();
		} else
			showMessage("Delete Failed!");
		userDao.closeConnection();
	}

	public User getUser() {
		return taskFrame.getUser();
	}

	public void isAutoLogin() throws SQLException {
		// TODO Auto-generated method stub
		UserDao userDao = new UserDao();
		List<User> users = userDao.findByIsAutoLogin(1);
		User user = null;
		if (users != null && !users.isEmpty())
			user = users.get(0);
		if (user != null) {
			loadUser(user);
			setUser(user);
			loginSuccessfully();
		}
		userDao.closeConnection();
	}

	private void loadUser(User user) throws SQLException {
		// TODO Auto-generated method stub
		TaskDao taskDao = new TaskDao();
		EventDao eventDao = new EventDao();
		EmailDao emailDao = new EmailDao();
		int userId = user.getUserId();
		user.setTasks(taskDao.findByUserId(userId));
		user.setEvents(eventDao.findByUserId(userId));
		user.setEmails(emailDao.findByUserId(userId));
		taskDao.closeConnection();
		eventDao.closeConnection();
		emailDao.closeConnection();
	}

	@SuppressWarnings("deprecation")
	private void login() throws SQLException {

		// before login,initialize all views
		taskFrame.init();

		User user = new User();
		UserDao userDao = new UserDao();
		String userName;
		String userPassword;
		userName = userPanel.getUserNameField().getText();
		userPassword = userPanel.getPasswordField().getText();
		List<User> users = userDao.findByUserName(userName);
		if (users == null || users.isEmpty()) {
			showMessage("Wrong username");
		} else {
			user = users.get(0);
			if (!user.getUserPassword().equals(userPassword))
				showMessage("Wrong password");
			else {
				loadUser(user);
				setUser(user);
				loginSuccessfully();
			}
		}
		userDao.closeConnection();
	}

	private void loginSuccessfully() {
		// TODO Auto-generated method stub
		showMessage("Login Successfully!");
		User user = getUser();

		setUserToPanel(user);
		// set component enabled
		userPanel.getLoginedUserLabel().setText(
				user.getUserName() + ", Welcome!");
		userPanel.getAutoLoginCheckBox().setEnabled(true);
		userPanel.getDeleteButton().setEnabled(true);
		JTabbedPane tabbedPane = taskFrame.getTabbedPane();
		tabbedPane.setEnabledAt(1, true);
		tabbedPane.setEnabledAt(2, true);
		tabbedPane.setEnabledAt(3, true);

		taskFrame.getTaskPanel().getTaskController().loginSuccessfully();
		taskFrame.getEventPanel().getEventController().loginSuccessfully();
		taskFrame.getEmailPanel().getEmailController().loginSuccessfully();

	}

	@SuppressWarnings("deprecation")
	private void modifyUser() throws SQLException {
		// TODO Auto-generated method stub
		User user = getUser();

		String name = user.getUserName();// keep the original name and
		// password
		String password = user.getUserPassword();
		String temp = null;
		temp = userPanel.getUserNameField().getText();
		if (temp == null || temp == "") {
			showMessage("Username can't be blank!");
			return;
		}
		user.setUserName(temp);
		temp = null;
		temp = userPanel.getPasswordField().getText();
		if (temp == null || temp == "") {
			showMessage("Password can't be blank!");
			return;
		}
		user.setUserPassword(temp);
		UserDao userDao = new UserDao();
		int i = userDao.update(user);
		if (i > 0) {
			showMessage("Modify Successfully!");
		} else {
			showMessage("Modify Failed");
			user.setUserName(name);
			user.setUserPassword(password);
			userPanel.getUserNameField().setText(name);
			userPanel.getPasswordField().setText("");
		}
		userDao.closeConnection();
	}

	private void setUser(User user) {
		// TODO Auto-generated method stub
		this.taskFrame.setUser(user);
	}

	private void setUserToPanel(User user) {
		userPanel.setUserName(user.getUserName());
		if (user.getIsAutoLogin() == 1)
			userPanel.getAutoLoginCheckBox().setSelected(true);
		else
			userPanel.getAutoLoginCheckBox().setSelected(false);
		userPanel.setPassword("");
	}

	private void showMessage(String message) {
		JOptionPane.showMessageDialog(null, message);
	}
}
